#include "stm32f10x.h"                  // Device header
#include "MyDMA.h"
#include "OLED.h"
#include "Serial.h"

uint16_t AD_Value[4] = { 0 };
extern uint16_t AD_slowdown;

void AD_Init(void)
{
    MyDMA_Init((uint32_t)AD_Value, 1);
    //Configure GPIOA ADC1 Clock 
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);

    //Configure Division
    RCC_ADCCLKConfig(RCC_PCLK2_Div6);

    //GPIOA Init
    GPIO_InitTypeDef GPIO_InitStruct;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AIN;
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;
    //| GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStruct);

    //指定读取的通道以及读取时长
    ADC_RegularChannelConfig(ADC1, ADC_Channel_0, 1, ADC_SampleTime_28Cycles5);
    //ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 2, ADC_SampleTime_28Cycles5);
    //ADC_RegularChannelConfig(ADC1, ADC_Channel_2, 3, ADC_SampleTime_28Cycles5);
    //ADC_RegularChannelConfig(ADC1, ADC_Channel_3, 4, ADC_SampleTime_28Cycles5);
    
    //ADC Init
    ADC_InitTypeDef ADC_InitStruct;
    ADC_InitStruct.ADC_Mode = ADC_Mode_Independent;
    ADC_InitStruct.ADC_DataAlign = ADC_DataAlign_Right;
    ADC_InitStruct.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
    ADC_InitStruct.ADC_ContinuousConvMode = ENABLE;
    ADC_InitStruct.ADC_ScanConvMode = ENABLE;                           //多通道就开启
    ADC_InitStruct.ADC_NbrOfChannel = 4;                                //仅在扫描模式下有效，输入几就是几个通道，在非扫描模式下只有序列一有效
    ADC_Init(ADC1, &ADC_InitStruct);

    ADC_DMACmd(ADC1, ENABLE);   
    ADC_Cmd(ADC1, ENABLE);

    //Calibration 校准以大幅提高电路稳定
    ADC_ResetCalibration(ADC1);
    while (ADC_GetResetCalibrationStatus(ADC1) == SET);
    ADC_StartCalibration(ADC1);
    while (ADC_GetCalibrationStatus(ADC1) == SET);

    ADC_SoftwareStartConvCmd(ADC1, ENABLE);
     
}

// 读取电压并显示
void AD_prc(void)
{
    if (AD_slowdown != 0)
    {
        return;
    }
    AD_slowdown = 20;
    OLED_ShowNum(1, 5, AD_Value[0], 4);
    Serial_WriteData(0x4003, AD_Value[0]);
}
